<template>
    <div>
      <!-- 搜索栏和操作按钮 -->
      <div class="topfunction">
        <el-input
          v-model="searchQuery"
          placeholder="请输入科室、医生搜索"
          clearable
          style="width: 200px;"
        />
        <el-button  class="custom-button" @click="handleAdd()">查询</el-button>
      </div>
  
      <!-- 表格 -->
      <el-table
        :data="currentPageData"
        height="690"
        border
        style="width: 100%"
        @row-click="handleRowClick"
        highlight-current-row
      >
        <el-table-column prop="appointmentId" label="#" width="50" />
        <el-table-column prop="patientId" label="病人id" width="180" />
        <el-table-column prop="appointmentTime" label="预约时间" width="180" />
        <el-table-column prop="paymentStatus" label="挂号缴费" />
        <el-table-column prop="status" label="就诊状态" />
        <!-- <el-table-column prop="email" label="电子邮件" /> -->
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button  class="custom-button"@click="editRow1(scope.row)">叫号</el-button>

            <el-button  class="custom-button"@click="editRow2(scope.row)" style="margin-top: 2.5%;">新增病历</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination 
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="filteredData.length"
          @current-change="handlePageChange"
          layout="prev, pager, next"
          class="custom-pagination"
        />
      </div>
  
      <!-- 弹窗：新增/编辑 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEditing ? '病历编辑' : '新增信息'"
        width="600px"
        style="height: 600px;"
      >
        <el-form :model="use4" label-width="80px" >
          <el-form-item label="病人id:">
            {{use4.patientId}}
          </el-form-item>
          <el-form-item label="医生id:">
            {{ use4.doctorId }}
          </el-form-item>
          <el-form-item label="日期">
            <el-input   v-model="mediecord.visitDate"/>
          </el-form-item>
          <el-form-item label="类型">
            <el-radio-group v-model="mediecord.type">
              <el-radio label="1">初诊</el-radio>
              <el-radio label="2">复诊</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="症状">
            <el-input   v-model="mediecord.illnessHistory" />
          </el-form-item>
          <el-form-item label="诊断结果">
            <el-input   v-model="mediecord.diagnosis" />
          </el-form-item>
          <el-form-item label="治疗方法">
            <el-input   v-model="mediecord.treatment" />
          </el-form-item>
          <el-form-item label="现病史">
            <el-input   v-model="mediecord.allergicHistory" />
          </el-form-item>
          
          
          <el-button type="primary" @click="juni1()" style="margin-left: 85%;background-color: green;">提交</el-button>
          
        </el-form>
      </el-dialog>
  
      <!-- 弹窗：查看详情 -->
      <el-dialog
        v-model="detailDialogVisible"
        title="查看详情"
        width="400px"
      >
        <el-descriptions bordered column="1">
          <el-descriptions-item label="日期">{{ selectedRow?.date }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ selectedRow?.name }}</el-descriptions-item>
          <el-descriptions-item label="地址">{{ selectedRow?.address }}</el-descriptions-item>
        </el-descriptions>
        <template #footer>
          <el-button type="primary" @click="detailDialogVisible = false">关闭</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script lang="ts">
  import { reactive, ref, computed, onMounted } from "vue";
  import type { Doctor } from "@/type/doctor";
  import axios from 'axios';
  export default {
    setup() {
      
      const doctors = ref<Doctor[]>([]);
      
      const tableData = reactive([
        { date: "2016-05-03", name: "王小虎", address: "上海市普陀区金沙江路 1518 弄" },
        { date: "2016-05-02", name: "赵小明", address: "北京市海淀区西三旗" },
        { date: "2016-05-04", name: "李雷", address: "广州市天河区车陂南路" },
        { date: "2016-05-05", name: "张三", address: "深圳市福田区"},
        { date: "2016-05-06", name: "李四", address: "成都市高新区" },
        { date: "2016-05-03", name: "王小虎", address: "上海市普陀区金沙江路 1518 弄" },
        { date: "2016-05-02", name: "赵小明", address: "北京市海淀区西三旗" },
        { date: "2016-05-04", name: "李雷", address: "广州市天河区车陂南路" },
        { date: "2016-05-05", name: "张三", address: "深圳市福田区"},
        { date: "2016-05-06", name: "李四", address: "成都市高新区" },
        { date: "2016-05-03", name: "王小虎", address: "上海市普陀区金沙江路 1518 弄" },
        { date: "2016-05-02", name: "赵小明", address: "北京市海淀区西三旗" },
        { date: "2016-05-04", name: "李雷", address: "广州市天河区车陂南路" },
        { date: "2016-05-05", name: "张三", address: "深圳市福田区"},
        { date: "2016-05-06", name: "李四", address: "成都市高新区" },
        { date: "2016-05-03", name: "王小虎", address: "上海市普陀区金沙江路 1518 弄" },
        { date: "2016-05-02", name: "赵小明", address: "北京市海淀区西三旗" },
        { date: "2016-05-04", name: "李雷", address: "广州市天河区车陂南路" },
        { date: "2016-05-05", name: "张三", address: "深圳市福田区"},
        { date: "2016-05-06", name: "李四", address: "成都市高新区" },
        // 继续添加更多数据...
      ]);
      let weww=ref("");
      let leng=0;
      const dialogVisible = ref(false);
      const detailDialogVisible = ref(false);
      const formData = reactive({ date: "", name: "", address: "" });
      let mediecord=reactive({ 
        recordId: 0,
        patientId: 0,
        doctorId: 0,
        visitDate: "",
        diagnosis: "",
        treatment: "",
        type: "",
        allergicHistory: "",
        illnessHistory: "",
        isComplete: 0,
        onsetDate: ""
      });
      const selectedRow = ref(null);
      const searchQuery = ref("");
      const isEditing = ref(false);
      // let res=reactive({ appointmentId: "", appointmentTime: "", doctorId: "" ,patientId:"",paymentStatus: "" ,status:""});
      let res={};
      const currentPage = ref(1); // 当前页码
      const pageSize = ref(13); // 每页显示条数
      let use4=reactive({ 
        appointmentId: 0,
        patientId: 0,
        doctorId: 0,
        appointmentTime: "",
        status: "",
        paymentStatus: ""
      });
      
      interface DataItem {
        appointmentId: string;
        appointmentTime: string;
        doctorId: string;
        patientId: string;
        paymentStatus: string;
        status: string;
  }
      let data01=ref<DataItem[]>([
        
        ]);
        
        const filteredData = computed(() => {
  return data01.value.filter((item) => {
    // 根据搜索查询进行筛选，同时排除未缴费和已确诊的记录
    return (
      (item.status.includes(searchQuery.value) || item.paymentStatus.includes(searchQuery.value)) &&
      item.paymentStatus !== '未缴费' && // 排除未缴费的
      item.status !== '已就诊' // 排除已确诊的
    );
  });
});

  
  const currentPageData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return filteredData.value.slice(start, end);
  });
      const handleAdd = () => {
        console.log(searchQuery)
      };
      const editRow1 = (row:any) => {

        let user2={
            appointmentId:row.appointmentId,
        }
        let user={
            queueId:1,
            appointmentId:row.appointmentId,
            calledStatus:"叫号",
            queueNumber:2,
            queueTime:0,
        }
        axios.post("http://zhsj.autumnclouds.cn/queue/query", user2)
              .then((response) => {       
                console.log(response.data.data[0].queueNumber);
                user.queueId=response.data.data[0].queueId;
                user.queueNumber=response.data.data[0].queueNumber
                user.queueTime=response.data.data[0].queueTime
                console.log(user);
        axios.put("http://zhsj.autumnclouds.cn/queue", user)
              .then((response) => {       
                console.log(response.data);
                alert("叫号中请等待!");
              })
              .catch((error) => {
                // alert("预约失败☹️,请勿重复预约");
              });
              })
              .catch((error) => {
                
              });
        
      };


      const editRow2 = (row:any) => {
        isEditing.value = true;
        Object.assign(formData, row);
        console.log(row);
        use4.appointmentId=row.appointmentId;
        use4.doctorId=row.doctorId;
        use4.patientId=row.patientId;
        use4.appointmentTime=row.appointmentTime
        use4.paymentStatus=row.paymentStatus
        dialogVisible.value = true;
      };
      const saveData = () => {
    // 确保 selectedRow.value 和 formData 都是有效的
    if (isEditing.value) {
      const selectedItem = tableData.find((item) => item === selectedRow.value);
      if (selectedItem && formData) {
        // 确保找到的 item 和 formData 都是有效对象
        Object.assign(selectedItem, formData);
      } else {
        console.error("无法更新数据，未找到选中的项或表单数据无效");
      }
    } else {
      if (formData) {
        // 确保 formData 是有效对象
        tableData.push({ ...formData });
      } else {
        console.error("无法添加数据，表单数据无效");
      }
    }
  
    // 隐藏对话框
    dialogVisible.value = false;
  };
  
  const juni1 = () => {
        console.log(mediecord);
        if(mediecord.allergicHistory==""||mediecord.diagnosis==""||mediecord.treatment=="")
        {
            alert("请填写信息完整!");
            return
        }
        if(mediecord.type=="1")mediecord.type="初诊"
        else mediecord.type="复诊"
        mediecord.doctorId=use4.doctorId;
        mediecord.patientId=use4.patientId;
        let randomNum = Math.floor(Math.random() * (100 - 1 + 1)) + 1;
        mediecord.recordId=randomNum;
        axios.post("http://zhsj.autumnclouds.cn/medicalrecord", mediecord)
              .then((response) => {       
                console.log(response.data);
                alert("编辑成功!")
              })
              .catch((error) => {
              });
        let ust={
            appointmentId:use4.appointmentId,
            patientId:mediecord.patientId,
            doctorId:use4.doctorId,
            appointmentTime:use4.appointmentTime,
            status:"已就诊",
            paymentStatus:use4.paymentStatus
        }
              axios.put("http://zhsj.autumnclouds.cn/appointment", ust)
              .then((response) => {       
                console.log(response.data);
                alert("编辑成功!")
              })
              .catch((error) => {
              });
        
  };
  const juni2 = () => {
  };
      const handleDelete = () => {
        if (selectedRow.value) {
          const index = tableData.indexOf(selectedRow.value);
          if (index !== -1) {
            tableData.splice(index, 1);
          }
          selectedRow.value = null;
          if ((currentPage.value - 1) * pageSize.value >= filteredData.value.length) {
            currentPage.value = Math.max(1, currentPage.value - 1);
          }
        }
      };
  
       const viewDetails = (row:any) => {
         selectedRow.value = row;
        //  detailDialogVisible.value = true;
       };
  
      const handleRowClick = (row:any) => {
        selectedRow.value = row;
        if(dialogVisible.value==false){
          detailDialogVisible.value = true;
        }
        
        console.log("点击一行元素");
      };
  
      const handlePageChange = (page:any) => {
        currentPage.value = page;
      };
      
      
      let token="";
      onMounted(() => {
            const wei = localStorage.getItem('username1');
            console.log(JSON.stringify(wei));
            const wei2 = localStorage.getItem('username2');
          let intWei: number = parseInt(wei2 ?? "0");  
            token=JSON.stringify(wei);
            let user2={
                doctorId:intWei,
            };
            axios.post("http://zhsj.autumnclouds.cn/appointment/query", user2)
              .then((response) => {       
                console.log(response.data.data);
                data01.value=response.data.data;
              })
              .catch((error) => {
                
              });
      });
    
  
  
      return {
        mediecord,
        leng,
        res,
        use4,
        tableData,
        dialogVisible,
        detailDialogVisible,
        formData,
        selectedRow,
        searchQuery,
        filteredData,
        currentPage,
        pageSize,
        currentPageData,
        handleAdd,
        handleDelete,
        editRow1,
        editRow2,
        viewDetails,
        saveData,
        handleRowClick,
        handlePageChange,
        isEditing,
        juni1,
        juni2,
      };
    },
  };
  </script>
  
  <style scoped>
  .el-input {
    margin-right: 10px;
  }
  
  .el-dialog {
    padding: 20px;
  }
  .topfunction{
    display: flex;
    align-items: right;
    margin-top: 10px;
    margin-bottom: 10px;
    margin-right: 20px;
    width: 100%;
    justify-content: flex-end; /* 靠右排列 */
  }
  .custom-button {
    background: linear-gradient(90deg, #74ebd5, #acb6e5); /* 渐变背景 */
    border: none;
    color: #fff;
    font-weight: bold;
    padding: 10px 20px;
    border-radius: 8px; /* 圆角按钮 */
    cursor: pointer;
    transition: all 0.3s ease; /* 动态过渡效果 */
  }
  
  .custom-button:hover {
    transform: scale(1.05); /* 鼠标悬停时放大 */
    box-shadow: 0 4px 10px rgba(116, 235, 213, 0.5); /* 光影效果 */
  }
  
  .custom-button:active {
    transform: scale(0.98); /* 点击时微微缩小 */
    box-shadow: none;
  }
  
  .custom-button:disabled {
    background: #e0e0e0; /* 禁用状态颜色 */
    color: #aaa;
    cursor: not-allowed;
    box-shadow: none;
  }
  
  .danger-button {
    background: linear-gradient(90deg, #acb6e5, #ff7272); /* 危险操作渐变色 */
  }
  
  .danger-button:hover {
    transform: scale(1.05);
    box-shadow: 0 4px 10px rgba(255, 114, 114, 0.5); /* 特殊危险操作光影 */
  }
  /* 分页容器样式：居中对齐 */
  .pagination-container {
    display: flex;
    justify-content: center; /* 水平居中 */
    margin-top: 20px; /* 与内容分隔距离 */
    gap: 12px; /* 分页按钮间距 */
  }
  
  /* 自定义分页主题样式 */
  .custom-pagination ::v-deep(.el-pager li) {
    background: linear-gradient(90deg, #74ebd5, #acb6e5); /* 主体渐变背景 */
    border: 1px solid #acb6e5; /* 边框 */
    color: #fff; /* 字体颜色 */
    border-radius: 4px; /* 圆角 */
    transition: all 0.3s ease; /* 平滑过渡 */
    margin: 0 8px; /* 增加间距 */
    padding: 8px 16px; /* 增加点击区域 */
  }
  
  /* 鼠标悬停时 */
  .custom-pagination ::v-deep(.el-pager li:hover) {
    background: linear-gradient(90deg, #acb6e5, #74ebd5); /* 鼠标悬停反转渐变 */
    box-shadow: 0 6px 12px rgba(116, 235, 213, 0.4); /* 更显著的光影效果 */
  }
  
  /* 激活状态：选中当前页 */
  .custom-pagination ::v-deep(.el-pager li.is-active) {
    background: linear-gradient(90deg, #acb6e5, #74ebd5); /* 加深颜色效果 */
    font-weight: bold; /* 加粗字体 */
    font-size: 1.1em; /* 略微增加字体大小 */
    color: #fff;
    border: 1px solid #74ebd5; /* 使用主题色作为边框 */
    box-shadow: 0 6px 14px rgba(116, 235, 213, 0.5); /* 增强光影 */
    transform: scale(1.1); /* 放大以凸显效果 */
  }
  
  /* 分页导航按钮：上一页/下一页 */
  .custom-pagination ::v-deep(.el-pagination__prev, .el-pagination__next) {
    background: linear-gradient(90deg, #74ebd5, #acb6e5); /* 渐变背景 */
    color: #fff; /* 字体颜色 */
    border-radius: 4px; /* 圆角 */
    padding: 8px 16px; /* 按钮尺寸 */
    margin: 0 8px; /* 导航按钮之间的间隔 */
    transition: all 0.3s ease;
    border: 1px solid #acb6e5;
  }
  
  /* 鼠标悬停时（上一页/下一页） */
  .custom-pagination ::v-deep(.el-pagination__prev:hover, .el-pagination__next:hover) {
    background: linear-gradient(90deg, #acb6e5, #74ebd5); /* 悬停渐变 */
    box-shadow: 0 6px 10px rgba(172, 182, 229, 0.3); /* 光影效果 */
  }
  
  /* 禁用状态 */
  .custom-pagination ::v-deep(.is-disabled) {
    background: #e0e0e0; /* 灰色背景 */
    color: #aaa; /* 禁用状态字体颜色 */
    cursor: not-allowed;
    box-shadow: none;
  }
  </style>